<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">
        <TreeTool :tree-node="company" :is-dept="false" @addEvent="addFn" @delEvent="delFn" @editEvent="editFn" />

        <el-tree :data="treeData" default-expand-all :props="{label:'name'}">
          <template v-slot="{data}">
            <TreeTool :tree-node="data" @addEvent="addFn" @delEvent="delFn" @editEvent="editFn" />
          </template>
        </el-tree>

      </el-card>
      <el-dialog :title="formData.id?'编辑部门':'新增部门'" :visible.sync="dialogFormVisible" @close="closeFn">
        <el-form ref="form" label-width="120px" :model="formData" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model.trim="formData.name" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model.trim="formData.code" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="manager">
            <el-select v-model="formData.manager" placeholder="请选择负责人">
              <el-option v-for="item in employees" :key="item.id" :label="item.username" :value="item.username" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="formData.introduce" type="textarea" placeholder="1-300个字符" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmFn">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { addDepartments, getDepartments, dalDepartment, editDepartment, getDepartmentDetailById } from '@/api/departments'
import { getEmployeesSimple } from '@/api/employees'
import TreeTool from './components/tree-tool.vue'
import { listToTree } from '@/utils'
// import { Message } from 'element-ui'
export default {
  components: {
    TreeTool
  },
  data() {
    const checkName = (rule, value, callback) => {
      let sameDepts
      if (this.formData.id) {
        sameDepts = this.depts.filter(item => {
          return item.id !== this.formData.id && item.pid === this.formData.pid
        })
      } else {
        sameDepts = this.depts.filter(item => {
          return item.pid === this.formData.pid
        })
      }
      const isREpeat = sameDepts.every(item => {
        return item.name !== value
      })

      console.log(59, isREpeat)
      if (isREpeat) {
        callback()
      } else {
        callback('不能通过')
      }
    }
    const checkCode = (rule, value, callback) => {
      let isREpeat
      if (this.formData.id) {
        isREpeat = this.depts.filter(item => {
          return item.id !== this.formData.id
        }).every(item => {
          return item.code !== value
        })
      } else {
        isREpeat = this.depts.every(item => {
          return item.code !== value
        })
      }

      console.log(59, isREpeat)
      if (isREpeat) {
        callback()
      } else {
        callback('不能通过')
      }
    }
    return {
      dialogFormVisible: false,
      company: {
        name: '传智播客',
        manager: '负责人',
        id: ''
      },

      treeData: [],
      formData: {
        code: '',
        name: '',
        introduce: '',
        pid: '',
        manager: ''
      },
      rules: {
        code: [
          { required: true, message: '部门编码必填', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码长度1-50', trigger: 'blur' },
          { validator: checkCode, message: '名部编码已存在，不能重复', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '部门名称必填', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称长度1-50', trigger: 'blur' },
          { validator: checkName, message: '名部门称已存在，不能重复', trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人必填', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍必填', trigger: 'blur' },
          { min: 1, max: 50, message: '部门介绍长度1-50', trigger: 'blur' }
        ]
      },
      employees: [],
      depts: []
    }
  },
  async created() {
    this.getDepartmentsList()
    this.employees = (await getEmployeesSimple())
  },
  methods: {
    async confirmFn() {
      // console.log(this.formData)
      await this.$refs.form.validate()
      if (this.formData.id) {
        await editDepartment(this.formData)
      } else {
        await addDepartments(this.formData)
      }
      this.getDepartmentsList()
      this.closeFn()
    },
    async getDepartmentsList() {
      const res = await getDepartments()
      // console.log(80, res)
      this.company.name = res.companyName
      this.treeData = listToTree(res.depts, '')
      this.depts = res.depts
    },
    closeFn() {
      this.dialogFormVisible = false
      this.formData = {
        manager: '',
        code: '',
        name: '',
        introduce: '',
        pid: ''
      }
      this.$refs.form.resetFields()
    },
    addFn(id) {
      console.log('id:', id)
      this.dialogFormVisible = true
      this.formData.pid = id
    },
    delFn(id) {
      console.log('delid:', id)
      this.$confirm('此操作将永久删除该部门, 是否继续?', '删除', {
        type: 'warning'
      }).then(async() => {
        console.log('确认')
        await dalDepartment(id)
        this.getDepartmentsList()
        // Message.success('成功删除')
      }).catch(() => {
        console.log('取消')
      })
    },
    async editFn(id) {
      console.log('id:', id)
      this.dialogFormVisible = true
      this.formData = await getDepartmentDetailById(id)
    }

  }
}
</script>
<style lang="scss" scoped>
.box-card {
  padding: 30px 100px;
}
</style>
